package com.igeek.boot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.igeek.boot.entity.User;
import com.igeek.boot.service.UserService;
import com.igeek.boot.vo.UserQueryVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author fengqq
 * @Description TODO
 * @Date 2024/8/22  10:04
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户模块的控制层")
public class UserController {
    @Autowired
    private UserService userService;

    //通过用户id查询用户信息
    @ApiOperation("通过用户id查询用户信息")
    @GetMapping("/{id}")
    public User findOne(@ApiParam("用户编号") @PathVariable("id") Long id){
        return userService.getById(id);
    }

    //分页+查询
    @ApiOperation("通过用户姓名查询用户列表+分页")
    @PostMapping ("/findAll/{current}/{size}")
    public Page<User> findAll(
            @ApiParam("当前页") @PathVariable("current") Integer current,
            @ApiParam("每页展示条目数") @PathVariable("size") Integer size,
            @ApiParam("查询条件") @RequestBody UserQueryVO queryVO
    ){

        //1.封装Page对象
        Page<User> page = new Page<>(current,size);

        //2.封装QueryWrapper查询条件对象
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //当第一个参数为true时则拼接条件
        queryWrapper.like(StringUtils.hasLength(queryVO.getName()),User::getName,queryVO.getName())
                .eq(!ObjectUtils.isEmpty(queryVO.getAge()),User::getAge,queryVO.getAge());
        //3.执行service
        Page<User> userPage = userService.page(page, queryWrapper);
        log.info("userPage:{}",userPage);
        log.info("records:{}",userPage.getRecords());
        log.info("当前页码:{}",userPage.getCurrent());
        log.info("每页展示条目数:{}",userPage.getSize());
        log.info("总记录数:{}",userPage.getTotal());
        log.info("总页码:{}",userPage.getPages());
        return userPage;
    }

    //添加用户
    @ApiOperation("添加用户")
    @PostMapping("/save")
    public boolean save(@ApiParam("用户信息") @RequestBody User user){
        return userService.save(user);
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/delete/{id}")
    public boolean delete(@ApiParam("用户编号") @PathVariable("id") Long id){
        return userService.removeById(id);
    }

    @ApiOperation("更新用户")
    @PutMapping("/update")
    public boolean update(@ApiParam("用户信息") @RequestBody User user){
        return userService.updateById(user);
    }

}














